<?php

namespace core\lib;

class verify{
	private $data;
	private $font;
	private $charset;
	public function __construct()
	{
		$this->data = null;
		$this->font = MVC . "/fonts/font.ttf";
		$this->charset='bcdefhkmnrstuvwxyABCDEFGHKMNPRSTUVWXY345689';
	}
	public function create($len=4, $fontSize=12, $width=0, $height=0)
	{
		if($width  == 0) $width = ($fontSize+5)*($len + 1);
        if($height == 0) $height = $fontSize * 3;
		//生成随机值
		$captcha = '';
        for($i = 0; $i < $len; $i++){
            $captcha .= substr($this->charset, mt_rand(0,strlen($this->charset)-1), 1);
        }
		//创建图片
		$image = imagecreatetruecolor($width, $height);
		//设置背景颜色
		$bgColor = imagecolorallocate($image, 255, 255, 255);
		//设置边框颜色
		$borderColor=imagecolorallocate($image, 128, 128, 128);
		//填充图片背景色
		imagefill($image, 0,0, $bgColor);
		//填充图片边框颜色
		imagerectangle($image, 0, 0, $width-1, $height-1, $borderColor);
		
		//生成图片文字
		for($i = 0; $i < $len; $i++){
			$angle = rand(-45, 45);
			$x = $fontSize / 2 + ($fontSize + 5) * $i;
			$y = $height / 1.5 - rand(2, 3);
			$color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
			//用规定字体向图像写入文本
			imagettftext($image, $fontSize, $angle, $x, $y, $color, $this->font,$captcha[$i]);
		}
		
		//加入干扰点
		for($i = 0; $i < 200; $i++){
			$color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
			$x = rand(0, $width);
			$y = rand(0, $height);
			imagesetpixel($image, $x, $y, $color);
		}
		//加入干扰直线
		for($i = 0; $i < 5; $i++){
			$color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
			$x1 = rand(0, $width);
			$y1 = rand(0, $height);
			$x2 = rand(0, $width);
			$y2 = rand(0, $height);
			imageline($image, $x1, $y1, $x2, $y2, $color);
		}
		
		$this->data = $image;

		return $captcha;
	}
	
	public function show()
	{
		header("Content-type: image/png");
		imagepng($this->data);
		imagedestroy($this->data);
	}
}